<?php
$whmcs_path="whmcs";

require($_SERVER['DOCUMENT_ROOT']."/".$whmcs_path."/dbconnect.php");

mysql_set_charset('utf8');

if (!isset($_SESSION["adminid"]))
{
	die("<center>Access denied</center>");
}

function get_admin_role($admin_id)
{
	$result = mysql_query("SELECT roleid FROM tbladmins WHERE (id='".intval($admin_id)."');");
	$r = mysql_fetch_assoc($result);
	return $r["roleid"];
}

function get_admin_name($admin_id)
{
	$result = mysql_query("SELECT username FROM tbladmins WHERE (id='".intval($admin_id)."');");
	$r = mysql_fetch_assoc($result);
	return $r["username"];
}

function read_status($admin_id, $article_id)
{
	return mysql_num_rows(mysql_query("SELECT * FROM mod_tracker WHERE (uid='".intval($admin_id)."' AND tid='".intval($article_id)."' AND type='ikb_read');"));
}

function preview($article, $num, $tail='&nbsp;...')
{
	$words = explode(" ", $article);
    $firstwords = array_slice($words, 0, $num);
    return implode(" ", $firstwords).$tail;
}

$gid = get_admin_role($_SESSION["adminid"]);

if (isset($_REQUEST["op"]) && $_REQUEST["op"]=="search")
{
	if (($gid>1) && ($_SESSION["adminid"]!=$_REQUEST["owner"]))
	{
		$_REQUEST["active"]=1;	
	}
	
	if (isset($_REQUEST["active"]) && ($_REQUEST["active"]==0))
	{
		$cond = "active=0";
	}
	else if (isset($_REQUEST["active"]) && ($_REQUEST["active"]==2))
	{
		$cond = "1";
	}
	else
	{
		$cond = "active=1";
	}
	
	if ($gid>1)
		$cond .= " AND ((id IN (SELECT DISTINCT tid FROM mod_tracker WHERE  (type='ikb_racl' AND uid='".$gid."'))) OR owner='".intval($_SESSION["adminid"])."' OR public=1)";
	
	if (isset($_REQUEST["public"]) && ($_REQUEST["public"]==1))
	{
		$cond .= " AND public=1";
	}
	else if (isset($_REQUEST["public"]) && ($_REQUEST["public"]==0))
	{
		$cond .= " AND public=0";
	}
			
	if (isset($_REQUEST["owner"]) && ($_REQUEST["owner"]>0))
	{
		$cond .= " AND owner=".intval($_REQUEST["owner"]);
	}
	
	if (isset($_REQUEST["updatedby"]) && ($_REQUEST["updatedby"]>0))
	{
		$cond .= " AND updatedby=".intval($_REQUEST["updatedby"]);
	}
		
	if ($_REQUEST["s"]!="")
	{
		$scond = "LIKE '%";	
		$s = preg_split("/[\s,]*\\\"([^\\\"]+)\\\"[\s,]*|" . "[\s,]*'([^']+)'[\s,]*|" . "[\s,]+/", htmlspecialchars_decode($_REQUEST["s"]), 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
		foreach ($s as $k)
		{
			$scond .= mysql_real_escape_string($k)."%";
		}
		$scond .="'";
		if (isset($_REQUEST["in"]) && ($_REQUEST["in"]==1))
			$cond .= " AND title ".$scond;
		else if (isset($_REQUEST["in"]) && ($_REQUEST["in"]==2))
			$cond .= " AND article ".$scond;
		else
			$cond .= " AND (article ".$scond." OR title ".$scond.")";
	}
	
	if (isset($_REQUEST["unread"]) && $_REQUEST["unread"]==1)
	{
		$cond .= " AND (id NOT IN (SELECT DISTINCT tid FROM mod_tracker WHERE  (type='ikb_read' AND uid='".intval($_SESSION["adminid"])."')))";
	}
	
	if (isset($_REQUEST["page"]) && intval($_REQUEST["page"])>0)
	{
		$page = intval($_REQUEST["page"]);
	}
	else
	{
		$page = 1;
	}
		
	$total = mysql_num_rows(mysql_query("SELECT id FROM mod_kb WHERE (".$cond.");"));	
	
	if ($total)	
	{
		$result = mysql_query("SELECT * FROM mod_kb WHERE (".$cond.") ORDER BY lastupdate DESC LIMIT ".(($page-1)*$perpage)." , ".$perpage."; ");		
		echo "<div style='border-top:1px solid #8FBCE9;padding-top:5px;'>
			<table width='100%'><tr><td>".$total." Articles Found, Page ".$page." of ".ceil($total/$perpage)."</td><td><div align='right'>Jump to Page: <select name='page' onchange='search(this.value);'>";
		for ($i=0;$i<ceil($total/$perpage);$i++)
		{
			echo "<option value='".($i+1)."' ";
			if ($i+1==$page)
				echo "selected";
			echo ">".($i+1);
		}
		echo "</select></div></td></tr></table>
		<table width=100% cellspacing=5 cellpadding=3 border=0>";
		
		while ($entry = mysql_fetch_assoc($result))
		{			
			echo "<tr><td align=left><a href=\"javascript:viewEntry('".$entry["id"]."', '".htmlspecialchars_decode($entry["title"])."');\">";
			if (read_status($_SESSION["adminid"],$entry["id"]))
				echo $entry["title"]."</a>";
			else
			{
				echo "<b>".$entry["title"]."</b></a>";
				if (!isset($_REQUEST["unread"]))
					echo "<i> (new)</i>";
			}
				
			echo "<br/>".preview(strip_tags(html_entity_decode($entry["article"])),15)."<br/><span style='color:#CCC;'>Created by ".get_admin_name($entry["owner"])." - Last edited by ".get_admin_name($entry["updatedby"])." at ".$entry["lastupdate"]."</span></td></tr>";
		}
		echo "</table></div>";
	
		if ($total>$perpage+1)
		{
			echo "<table width='100%'><tr><td width='50%' align='right'>";
			if ($page>1)
				echo "<a href=\"javascript:search('".($page-1)."');\"'><< Previous</a>";
			else
				echo "<< Previous";
			echo "</td><td width='50%' align='left'>";
			if ($page*$perpage<$total && ($page-1)*$perpage<$total)
				echo "<a href=\"javascript:search('".($page+1)."');\"'>Next >></a>";
			else
				echo "Next >>";
			echo "</td></tr></table>";
		}
	}
	else
		exit("<div id=infobox>Found nothing!</div>");	
}
else if (isset($_REQUEST["op"]) && $_REQUEST["op"]=="view_entry" && isset($_REQUEST["id"]))
{	
	$result = mysql_query("SELECT * FROM mod_kb WHERE (id='".intval($_REQUEST["id"])."');");
	
	if (mysql_error())
	{
		$read = 0;
	}
	else
	{
		$entry = mysql_fetch_assoc($result);	
		
		if ((get_admin_role($_SESSION["adminid"])==1) || ($_SESSION["adminid"]==$entry["owner"]))
		{
			$read = 1;
			$write = 1;
		}
		else
		{	
			if ($entry["public"]==1)
			{
				$read = 1;
			}
			else
			{	
				$read = mysql_num_rows(mysql_query("SELECT * FROM mod_tracker WHERE (type='ikb_racl' AND uid='".get_admin_role($_SESSION["adminid"])."' AND tid='".intval($id)."');"));
			}
			$write = mysql_num_rows(mysql_query("SELECT * FROM mod_tracker WHERE (type='ikb_wacl' AND uid='".get_admin_role($_SESSION["adminid"])."' AND tid='".intval($id)."');"));
		}
	}

	if ($read)
	{
		echo htmlspecialchars_decode($entry["article"])."<div style='border-top:1px solid #CCC;padding-top:5px;'>
			<table width=100% cellspacing=0 cellpadding=0><tr><td align='left' style='color:#CCC;'>Created by ".get_admin_name($entry["owner"])."</td><td align='right' style='color:#CCC;'>Last updated by ".get_admin_name($entry["updatedby"])." at ".$entry["lastupdate"]."</span>";
		if ($write)
			echo " <a href=\"javascript:loadEditForm(".intval($_REQUEST["id"]).");\">[Edit]</a>";
		echo "</td></tr></table></div>";
	}
	else
	{
		echo "<div id=infobox>You don't have read access to this article!</div>";
	}
}
else if (isset($_REQUEST["op"]) && $_REQUEST["op"]=="edit_entry" && isset($_REQUEST["id"]))
{
	$result = mysql_query("SELECT * FROM mod_kb WHERE (id='".intval($_REQUEST["id"])."');");
	
	if (mysql_error())
	{
		$write = 0;
	}
	else
	{
		$entry = mysql_fetch_assoc($result);	
		
		if ((get_admin_role($_SESSION["adminid"])==1) || ($_SESSION["adminid"]==$entry["owner"]))		
			$write = 1;
		else
			$write = mysql_num_rows(mysql_query("SELECT * FROM mod_tracker WHERE (type='ikb_wacl' AND uid='".get_admin_role($_SESSION["adminid"])."' AND tid='".intval($id)."');"));
	}
	if ($write)
	{
		echo "<textarea name='article' rows=18 style='width:100%'>".$entry["article"]."</textarea><br/><center><input type='button' value='Save' class='button' onclick='javascript:save();'><input type='button' value='Delete' class='button' onclick=\"javascript:deleteEntry('".$entry["id"]."');\"></center>";
	}
	else
		exit("<div id=infobox>Permission denied!</div>");
}
else if (isset($_REQUEST["op"]) && $_REQUEST["op"]=="delete_entry" && isset($_REQUEST["id"]))
{
	echo "deleted";
}
else if (isset($_REQUEST["op"]) && ($_REQUEST["op"]=="load_add_form"))
{
?>
	<table width=100% cellspacing=1 cellpadding=0 bgcolor=#8FBCE9>
	<tr><td bgcolor=#ffffff>
		<table width=100% cellpadding=2>					
		<tr><td align='right' width='120'>Title: </td><td class='fieldarea'><input type='text' id='title' size=70></td></tr>
		<tr><td align='right'>Active: </td><td class='fieldarea'><select id='active'><option value='1' selected>Yes<option value='0'>No</select></td></tr>
		<tr><td align='right'>Public: </td><td class='fieldarea'><select id='public'><option value='0' selected>No<option value='1'>Yes</select></td></td></tr>
		<tr><td align='right'>Language: </td><td class='fieldarea'><select id='language'><option value='vi' selected>Vietnamese<option value='en'>English</select></td></tr>		
		<tr><td align='right'>Translated version: </td><td class='fieldarea' id='selectLang'><input type='button' value='Set' class='button' onclick='getLanguageForm();'></td></tr>	
		</table>
	</td></tr>
	</table>
	<br/><textarea id='article' rows=18 style='width:100%'></textarea>
	<br/><center><table cellspacing=1 cellpadding=3 bgcolor='#cccccc'>
				<tr bgcolor='#efefef' style='text-align:center;font-weight:bold'><td>Admin Roles</td><td width='50'>Read</td><td width='50'>Write</td></tr>
<?php
	$result = mysql_query("SELECT * FROM tbladminroles WHERE id>1;");	
	while ($admins = mysql_fetch_assoc($result))
	{
		echo "<tr bgcolor='#ffffff' style='text-align:center;'>
			<td>".$admins["name"]."</td>
			<td><input type='checkbox' name='racl_".$admins["id"]."' value='1'></td>
			<td><input type='checkbox' name='wacl_".$admins["id"]."' value='1'></td>
			</tr>";
	}
	echo "</table><br/>
	<input type='button' value='Create Entry' class='button'></center>";
}
else if (isset($_REQUEST["op"]) && ($_REQUEST["op"]=="load_language_list"))
{
	$result = mysql_query("SELECT title, id FROM mod_kb WHERE (language!='".mysql_real_escape_string($_REQUEST["clang"])."' AND tid='0');");
	echo "<select name='tid' id='tid'>";
	echo "<option value='0' selected>--none--";
	while ($entry = mysql_fetch_assoc($result))
	{
		echo "<option value='".$entry["id"]."'>".$entry["title"];
	}
	echo "</select>";
}
else
{
	exit("<div id=infobox>Invalid request!</div>");
}
?>